// SPDX-License-Identifier: MIT
// Copyright 2020 NXP

#include "lvgl.h"
#include "custom.h"
#include <stdlib.h>
#include <stdint.h>
#include "bsp.h"
#include "FreeRTOS.h"
#include "queue.h"

#define GRID_ROWS 6
#define GRID_COLS 6
#define ICON_SIZE 50
#define ICON_TYPES 10
#define MAX_PATH_POINTS 4
#define TOTAL_LEVELS 5

static uint16_t game_grid[GRID_ROWS][GRID_COLS];
static lv_obj_t *icon_btns[GRID_ROWS][GRID_COLS];
/* 全局定义 */
static lv_obj_t *icon_labels[GRID_ROWS][GRID_COLS] = {0}; // 存储所有标签对象
static lv_point_t first_select = {-1, -1};

static lv_obj_t *path_line = NULL;
static lv_point_t path_points[MAX_PATH_POINTS];
static uint8_t path_point_count = 0;

static lv_obj_t *main_menu_screen = NULL;
static lv_obj_t *game_screen = NULL;
static lv_obj_t *label_level = NULL;
static lv_obj_t *label_pairs = NULL;
static lv_obj_t *win_dialog = NULL; // 通关对话框指针

static uint8_t current_level = 1;
static uint16_t pairs_remaining = 0;

static bool ai_enabled = false;
static lv_timer_t *ai_timer = NULL;

QueueHandle_t buzzGameQueue; // define a queue handler

int toneTable[] = {0, 523, 0, 0, 587, 0, 0, 659, 0, 0, 698, 0, 0, 784, 0, 0, 880, 0, 0, 988, 0, 0, 1047, 0, 0};

// 明确初始化 lv_color_t 的 ch 成员（LVGL 7.x/8.x 通用）
static const lv_color_t ICON_COLORS[ICON_TYPES + 1] = {
    [0] = {.ch.red = 0x00, .ch.green = 0x00, .ch.blue = 0x00},  // 空块
    [1] = {.ch.red = 0xFF, .ch.green = 0x00, .ch.blue = 0x00},  // 红色
    [2] = {.ch.red = 0x00, .ch.green = 0xFF, .ch.blue = 0x00},  // 绿色
    [3] = {.ch.red = 0x00, .ch.green = 0x00, .ch.blue = 0xFF},  // 蓝色
    [4] = {.ch.red = 0xFF, .ch.green = 0xFF, .ch.blue = 0x00},  // 黄色
    [5] = {.ch.red = 0x80, .ch.green = 0x00, .ch.blue = 0x40},  // 深紫红色
    [6] = {.ch.red = 0x00, .ch.green = 0xBF, .ch.blue = 0xFF},  // 天蓝色
    [7] = {.ch.red = 0xFF, .ch.green = 0xA5, .ch.blue = 0x00},  // 橙色
    [8] = {.ch.red = 0x60, .ch.green = 0x60, .ch.blue = 0x60},  // 深灰色
    [9] = {.ch.red = 0xFF, .ch.green = 0x00, .ch.blue = 0xFF},  // 品红色
    [10] = {.ch.red = 0xFA, .ch.green = 0xFB, .ch.blue = 0xF2}, // 紫罗兰色

};
/* 函数声明 */
static void shuffle_icons(void);
static void create_game_ui(void);
static void create_start_menu(void);
static void custom_start_game(void);
static void icon_event_cb(lv_event_t *e);
static bool is_line_clear(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
static bool can_connect(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
static void draw_path_line(void);
static void hide_path_line_cb(lv_timer_t *timer);
static void grid_to_screen(uint16_t x, uint16_t y, lv_point_t *pt);
void buzz_event(int toneSetSelect, int delayTime);

// 通关相关函数声明
static void show_win_dialog(void);
static void return_to_main(lv_event_t *e);
static void go_to_next_level(lv_event_t *e);

typedef enum
{
    LEVEL_LOCKED,
    LEVEL_UNLOCKED,
    LEVEL_COMPLETED
} level_status_t;

static level_status_t level_status[TOTAL_LEVELS] = {
    LEVEL_UNLOCKED, LEVEL_LOCKED, LEVEL_LOCKED, // 初始状态可修改，这里保持原设置
    LEVEL_LOCKED, LEVEL_LOCKED};

/* 初始化入口 */
void custom_init(lv_ui *ui)
{

    ai_enabled = false; // 确保每次初始化时，AI 开关是关闭的
    create_game_ui();
    create_start_menu();
}

/* 主菜单界面 */
static void start_game_cb(lv_event_t *e)
{

    buzz_event(7,100);
    uint8_t level = (uint8_t)(uintptr_t)lv_event_get_user_data(e);
    current_level = level;
    if (win_dialog)
    {
        lv_obj_del(win_dialog);
        win_dialog = NULL; // 重要：将指针置为NULL
    }
    lv_scr_load(game_screen);
    custom_start_game();
}

void buzz_event(int toneSetSelect, int delayTime)
{
    tone(toneTable[toneSetSelect]);
    vTaskDelay(delayTime);
    toneOff();
}

/* 游戏菜单界面初始化 */
static void create_start_menu(void)
{
    // 释放旧界面，防止重复生成控件导致内存泄露
    if (main_menu_screen)
    {
        lv_obj_del(main_menu_screen);
        main_menu_screen = NULL;
    }

    // 创建主屏幕
    main_menu_screen = lv_obj_create(NULL);
    lv_obj_set_size(main_menu_screen, 480, 320);
    lv_obj_center(main_menu_screen);
    lv_obj_set_style_pad_all(main_menu_screen, 0, 0);
    lv_obj_clear_flag(main_menu_screen, LV_OBJ_FLAG_SCROLLABLE);

    // 背景渐变色样式
    lv_style_t bg_style;
    lv_style_init(&bg_style);
    lv_style_set_bg_color(&bg_style, lv_color_hex(0xE0F7FA));
    lv_style_set_bg_grad_color(&bg_style, lv_color_hex(0xFFFFFF));
    lv_style_set_bg_grad_dir(&bg_style, LV_GRAD_DIR_VER);
    lv_style_set_bg_opa(&bg_style, LV_OPA_COVER);
    lv_obj_add_style(main_menu_screen, &bg_style, 0);

    // 添加游戏标题
    lv_obj_t *title = lv_label_create(main_menu_screen);
    lv_label_set_text(title, "🎮 Link Game 🎮");
    lv_obj_set_style_text_font(title, &lv_font_montserrat_24, 0);
    lv_obj_set_style_text_color(title, lv_color_hex(0x1A237E), 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 20);

    // 关卡坐标
    static const lv_point_t level_positions[TOTAL_LEVELS] = {
        {60, 130}, {150, 150}, {240, 160}, {320, 150}, {400, 170}};

    // 连线
    for (uint8_t i = 0; i < TOTAL_LEVELS - 1; i++)
    {
        lv_point_t line_points[2] = {
            {level_positions[i].x + 20, level_positions[i].y + 20},
            {level_positions[i + 1].x + 20, level_positions[i + 1].y + 20}};

        lv_obj_t *line = lv_line_create(main_menu_screen);
        lv_line_set_points(line, line_points, 2);
        lv_obj_set_style_line_width(line, 3, LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_obj_set_style_line_rounded(line, true, LV_PART_MAIN | LV_STATE_DEFAULT);

        if (level_status[i] == LEVEL_COMPLETED && level_status[i + 1] == LEVEL_COMPLETED)
        {
            lv_obj_set_style_line_color(line, lv_color_hex(0x42A5F5), LV_PART_MAIN | LV_STATE_DEFAULT);
        }
        else
        {
            lv_obj_set_style_line_color(line, lv_color_hex(0xB0BEC5), LV_PART_MAIN | LV_STATE_DEFAULT);
        }

        lv_obj_clear_flag(line, LV_OBJ_FLAG_HIDDEN);
    }

    // 创建关卡按钮
    for (uint8_t i = 0; i < TOTAL_LEVELS; ++i)
    {
        lv_obj_t *btn = lv_btn_create(main_menu_screen);
        lv_obj_set_size(btn, 40, 40);
        lv_obj_set_style_radius(btn, LV_RADIUS_CIRCLE, 0);
        lv_obj_set_pos(btn, level_positions[i].x, level_positions[i].y);
        lv_obj_add_event_cb(btn, start_game_cb, LV_EVENT_CLICKED, (void *)(uintptr_t)(i + 1));

        // 阴影效果
        lv_obj_set_style_shadow_width(btn, 12, 0);
        lv_obj_set_style_shadow_ofs_y(btn, 6, 0);
        lv_obj_set_style_shadow_opa(btn, LV_OPA_50, 0);

        // 状态颜色美化
        switch (level_status[i])
        {
        case LEVEL_COMPLETED:
            lv_obj_set_style_bg_color(btn, lv_color_hex(0x4CAF50), 0); // 成功绿
            lv_obj_set_style_shadow_color(btn, lv_color_hex(0x388E3C), 0);
            break;
        case LEVEL_UNLOCKED:
            lv_obj_set_style_bg_color(btn, lv_color_hex(0x2196F3), 0); // 蓝色可用
            lv_obj_set_style_shadow_color(btn, lv_color_hex(0x1565C0), 0);
            break;
        case LEVEL_LOCKED:
        default:
            lv_obj_set_style_bg_color(btn, lv_color_hex(0xBDBDBD), 0); // 灰色锁定
            lv_obj_set_style_shadow_color(btn, lv_color_hex(0x9E9E9E), 0);
            lv_obj_clear_flag(btn, LV_OBJ_FLAG_CLICKABLE);
            break;
        }

        // 数字标签
        lv_obj_t *label = lv_label_create(btn);
        char txt[4];
        snprintf(txt, sizeof(txt), "%d", i + 1);
        lv_label_set_text(label, txt);
        lv_obj_set_style_text_color(label, lv_color_white(), 0);
        lv_obj_set_style_text_font(label, &lv_font_montserrat_16, 0);
        lv_obj_center(label);

        // 浮动动画（上下）
        lv_anim_t a;
        lv_anim_init(&a);
        lv_anim_set_var(&a, btn);
        lv_anim_set_values(&a, level_positions[i].y - 5, level_positions[i].y + 5);
        lv_anim_set_time(&a, 1000 + (i * 300));
        lv_anim_set_playback_time(&a, 1000 + (i * 300));
        lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
        lv_anim_set_path_cb(&a, lv_anim_path_ease_in_out);
        lv_anim_set_exec_cb(&a, (lv_anim_exec_xcb_t)lv_obj_set_y);
        lv_anim_start(&a);

        lv_obj_move_foreground(btn);
    }

    lv_scr_load(main_menu_screen);
}

static void ai_auto_link_cb(lv_timer_t *timer)
{
    if (!ai_enabled || pairs_remaining == 0)
        return;

    for (uint16_t y1 = 0; y1 < GRID_ROWS; y1++)
    {
        for (uint16_t x1 = 0; x1 < GRID_COLS; x1++)
        {
            if (game_grid[y1][x1] == 0)
                continue;
            for (uint16_t y2 = 0; y2 < GRID_ROWS; ++y2)
            {
                for (uint16_t x2 = 0; x2 < GRID_COLS; ++x2)
                {
                    if ((x1 != x2 || y1 != y2) &&
                        game_grid[y2][x2] == game_grid[y1][x1] &&
                        can_connect(x1, y1, x2, y2))
                    {

                        buzz_event(2,50);
                        draw_path_line(); // 显示线条
                        game_grid[y1][x1] = 0;
                        game_grid[y2][x2] = 0;

                        lv_obj_add_flag(icon_btns[y1][x1], LV_OBJ_FLAG_HIDDEN);
                        lv_obj_add_flag(icon_btns[y2][x2], LV_OBJ_FLAG_HIDDEN);

                        pairs_remaining--;
                        lv_label_set_text_fmt(label_pairs, "Remains:%d", pairs_remaining);

                        if (pairs_remaining == 0)
                        {
                            printf("current_level:%d\n", current_level);
                            // 更新关卡状态：当前关卡完成，下一关解锁
                            if (current_level <= TOTAL_LEVELS)
                            {
                                level_status[current_level - 1] = LEVEL_COMPLETED;
                                if (current_level < TOTAL_LEVELS &&
                                    level_status[current_level + 1] == LEVEL_LOCKED)
                                {
                                    level_status[current_level] = LEVEL_UNLOCKED;
                                }
                            }

                            for (uint8_t i = 0; i < TOTAL_LEVELS; i++)
                            {
                                printf("%d\n", level_status[i]);
                            }
                            show_win_dialog(); // 显示通关对话框
                        }

                        return;
                    }
                }
            }
        }
    }
}

// 返回主菜单回调函数
static void return_to_main_menu_cb(lv_event_t *e)
{
    buzz_event(8,100);
    lv_scr_load(main_menu_screen);
    create_start_menu();
}

// 提示按钮的回调
static void show_hint_cb(lv_event_t *e)
{
    for (uint16_t y1 = 0; y1 < GRID_ROWS; ++y1)
    {
        for (uint16_t x1 = 0; x1 < GRID_COLS; ++x1)
        {
            if (game_grid[y1][x1] == 0)
                continue;
            for (uint16_t y2 = 0; y2 < GRID_ROWS; ++y2)
            {
                for (uint16_t x2 = 0; x2 < GRID_COLS; ++x2)
                {
                    if ((x1 != x2 || y1 != y2) && game_grid[y2][x2] == game_grid[y1][x1])
                    {
                        if (can_connect(x1, y1, x2, y2))
                        {
                            buzz_event(4,50);
                          
                            // 显示提示路径（虚线样式）
                            if (!path_line)
                            {
                                path_line = lv_line_create(lv_scr_act());
                                lv_obj_set_style_line_width(path_line, 3, 0);
                                lv_obj_set_style_line_rounded(path_line, true, 0);
                            }

                            lv_line_set_points(path_line, path_points, path_point_count);
                            lv_obj_clear_flag(path_line, LV_OBJ_FLAG_HIDDEN);

                            lv_obj_set_style_line_color(path_line, lv_color_hex(0x2196F3), 0); // 蓝色
                            lv_obj_set_style_line_dash_gap(path_line, 4, 0);                   // 设置虚线间隔
                            lv_obj_set_style_line_dash_width(path_line, 4, 0);

                            lv_timer_t *timer = lv_timer_create(hide_path_line_cb, 800, NULL);
                            lv_timer_set_repeat_count(timer, 1);

                              buzz_event(4,50);
                            return;
                        }
                    }
                }
            }
        }
    }
}

static void ai_btn_event_cb(lv_event_t *e)
{
    // 切换 AI 开关状态
    ai_enabled = !ai_enabled;

    // 获取按钮中的文本标签并更新其内容
    lv_obj_t *label = lv_obj_get_child(lv_event_get_target(e), 0);
    lv_label_set_text(label, ai_enabled ? "AI: On" : "AI: Off");
     buzz_event(1,100);
}

/* 游戏界面 */
static void create_game_ui(void)
{
    ai_timer = lv_timer_create(ai_auto_link_cb, 100, NULL); // 每秒运行一次
    lv_timer_set_repeat_count(ai_timer, -1);                // 无限次

    game_screen = lv_obj_create(NULL);

    // 左边状态栏（固定尺寸，禁止滚动）
    lv_obj_t *info_box = lv_obj_create(game_screen);
    lv_obj_set_size(info_box, 120, 320);
    lv_obj_align(info_box, LV_ALIGN_LEFT_MID, 0, 0);
    lv_obj_clear_flag(info_box, LV_OBJ_FLAG_SCROLLABLE); // 禁止滚动
                                                         // 关卡标签
    label_level = lv_label_create(info_box);
    lv_label_set_text_fmt(label_level, "Level:%d", current_level);
    lv_obj_align(label_level, LV_ALIGN_TOP_LEFT, 10, 10);
    lv_obj_set_width(label_level, 100); // 限制宽度防止溢出
                                        // 剩余配对标签
    label_pairs = lv_label_create(info_box);
    lv_label_set_text_fmt(label_pairs, "Remains:%d", pairs_remaining);
    lv_obj_align(label_pairs, LV_ALIGN_TOP_LEFT, 0, 45);
    lv_obj_set_width(label_pairs, 100);

    // 游戏网格
    int x_offset = 120 + (480 - 120 - GRID_COLS * ICON_SIZE) / 2;
    int y_offset = (320 - GRID_ROWS * ICON_SIZE) / 2;
    // 底部返回按钮（320-40-10=270px位置）
    lv_obj_t *back_btn = lv_btn_create(info_box);
    lv_obj_set_size(back_btn, 80, 30);
    lv_obj_set_pos(back_btn, 0, 220);
    lv_obj_add_event_cb(back_btn, return_to_main_menu_cb, LV_EVENT_CLICKED, NULL);

    lv_obj_set_style_radius(back_btn, 4, 0);
    lv_obj_set_style_bg_color(back_btn, lv_color_hex(0xF44336), 0);
    lv_obj_set_style_border_width(back_btn, 0, 0);
    lv_obj_set_style_text_color(back_btn, lv_color_hex(0xFFFFFF), 0);

    lv_obj_t *ai_btn = lv_btn_create(info_box);
    lv_obj_set_size(ai_btn, 80, 30);
    lv_obj_set_pos(ai_btn, 0, 140);
    lv_obj_set_style_radius(ai_btn, 4, 0);
    lv_obj_set_style_bg_color(ai_btn, lv_color_hex(0x9C27B0), 0); // 紫色
    lv_obj_set_style_text_color(ai_btn, lv_color_white(), 0);

    lv_obj_t *ai_label = lv_label_create(ai_btn);
    lv_label_set_text(ai_label, "AI: Off");
    lv_obj_center(ai_label);

    lv_obj_add_event_cb(ai_btn, ai_btn_event_cb, LV_EVENT_CLICKED, NULL);

    lv_obj_t *hint_btn = lv_btn_create(info_box);
    lv_obj_set_size(hint_btn, 80, 30);
    lv_obj_set_pos(hint_btn, 0, 180); // 比 Menu 按钮高一点（比如 180px）
    lv_obj_set_style_radius(hint_btn, 4, 0);
    lv_obj_set_style_bg_color(hint_btn, lv_color_hex(0x03A9F4), 0);
    lv_obj_set_style_border_width(hint_btn, 0, 0);
    lv_obj_set_style_text_color(hint_btn, lv_color_hex(0xFFFFFF), 0);

    lv_obj_t *hint_label = lv_label_create(hint_btn);
    lv_label_set_text(hint_label, "Hint");
    lv_obj_center(hint_label);

    lv_obj_add_event_cb(hint_btn, show_hint_cb, LV_EVENT_CLICKED, NULL);

    lv_obj_t *back_label = lv_label_create(back_btn);
    lv_label_set_text(back_label, "Menu");
    lv_obj_center(back_label);

    for (uint16_t r = 0; r < GRID_ROWS; ++r)
    {
        for (uint16_t c = 0; c < GRID_COLS; ++c)
        {
            lv_obj_t *btn = lv_btn_create(game_screen);
            lv_obj_set_size(btn, ICON_SIZE, ICON_SIZE);
            lv_obj_set_pos(btn, x_offset + c * ICON_SIZE, y_offset + r * ICON_SIZE);
            lv_obj_add_event_cb(btn, icon_event_cb, LV_EVENT_CLICKED, NULL);

            lv_obj_set_style_radius(btn, 8, 0);
            lv_obj_set_style_border_width(btn, 2, 0);
            lv_obj_set_style_border_color(btn, lv_color_hex(0x666666), 0);

            icon_btns[r][c] = btn;
        }
    }
}

/* 游戏开始时初始化（显示数字） */

static void custom_start_game(void)
{
    ai_enabled = false; // 每次开始游戏时，AI 默认关闭
    srand((unsigned int)current_level + 2000);
    shuffle_icons();
    pairs_remaining = (GRID_ROWS * GRID_COLS) / 2;

    lv_label_set_text_fmt(label_level, "Level:%d", current_level);
    lv_label_set_text_fmt(label_pairs, "Remains:%d", pairs_remaining);

    for (uint16_t r = 0; r < GRID_ROWS; ++r)
    {
        for (uint16_t c = 0; c < GRID_COLS; ++c)
        {
            uint16_t type = game_grid[r][c];

            // 先清理旧标签（如果存在）
            if (icon_labels[r][c])
            {
                lv_obj_del(icon_labels[r][c]);
                icon_labels[r][c] = NULL;
            }

            if (type == 0)
            {
                lv_obj_add_flag(icon_btns[r][c], LV_OBJ_FLAG_HIDDEN);
            }
            else
            {
                lv_obj_clear_flag(icon_btns[r][c], LV_OBJ_FLAG_HIDDEN);
                // 设置颜色
                lv_color_t color = {
                    .ch.red = ICON_COLORS[type].ch.red,
                    .ch.green = ICON_COLORS[type].ch.green,
                    .ch.blue = ICON_COLORS[type].ch.blue};
                lv_obj_set_style_bg_color(icon_btns[r][c], color, 0);

                // 创建新标签并保存引用
                icon_labels[r][c] = lv_label_create(icon_btns[r][c]);
                lv_label_set_text_fmt(icon_labels[r][c], "%d", type);
                lv_obj_set_style_text_color(icon_labels[r][c], lv_color_white(), 0);
                lv_obj_set_style_text_font(icon_labels[r][c], &lv_font_montserrat_16, 0);
                lv_obj_center(icon_labels[r][c]);
            }
        }
    }
}
/* 洗牌图标 */
static void shuffle_icons(void)
{
    uint16_t total = GRID_ROWS * GRID_COLS;
    uint16_t icons[total];
    uint16_t i, k = 0;

    for (i = 0; i < total / 2; ++i)
    {
        uint16_t type = (i % ICON_TYPES) + 1;
        icons[k++] = type;
        icons[k++] = type;
    }

    for (i = total - 1; i > 0; --i)
    {
        uint16_t j = rand() % (i + 1);
        uint16_t temp = icons[i];
        icons[i] = icons[j];
        icons[j] = temp;
    }

    k = 0;
    for (uint16_t r = 0; r < GRID_ROWS; ++r)
    {
        for (uint16_t c = 0; c < GRID_COLS; ++c)
        {
            game_grid[r][c] = icons[k++];
        }
    }
}

/* 坐标转换为屏幕中心点 */
static void grid_to_screen(uint16_t x, uint16_t y, lv_point_t *pt)
{
    int x_offset = 120 + (480 - 120 - GRID_COLS * ICON_SIZE) / 2;
    int y_offset = (320 - GRID_ROWS * ICON_SIZE) / 2;
    pt->x = x_offset + x * ICON_SIZE + ICON_SIZE / 2;
    pt->y = y_offset + y * ICON_SIZE + ICON_SIZE / 2;
}

/* 检查是否是连通路径 */
static bool is_line_clear(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2)
{
    if (x1 == x2)
    {
        uint16_t min_y = y1 < y2 ? y1 : y2;
        uint16_t max_y = y1 > y2 ? y1 : y2;
        for (uint16_t y = min_y + 1; y < max_y; ++y)
            if (game_grid[y][x1] != 0)
                return false;
        return true;
    }
    else if (y1 == y2)
    {
        uint16_t min_x = x1 < x2 ? x1 : x2;
        uint16_t max_x = x1 > x2 ? x1 : x2;
        for (uint16_t x = min_x + 1; x < max_x; ++x)
            if (game_grid[y1][x] != 0)
                return false;
        return true;
    }
    return false;
}

/* 判断是否可以连接 + 记录路径 */
static bool can_connect(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2)
{
    if (game_grid[y1][x1] != game_grid[y2][x2] || (x1 == x2 && y1 == y2))
        return false;

    lv_point_t pt1, pt2, pt3, pt4;
    path_point_count = 0;

    if (is_line_clear(x1, y1, x2, y2))
    {
        grid_to_screen(x1, y1, &pt1);
        grid_to_screen(x2, y2, &pt2);
        path_points[0] = pt1;
        path_points[1] = pt2;
        path_point_count = 2;
        return true;
    }

    if (game_grid[y1][x2] == 0 && is_line_clear(x1, y1, x2, y1) && is_line_clear(x2, y1, x2, y2))
    {
        grid_to_screen(x1, y1, &pt1);
        grid_to_screen(x2, y1, &pt2);
        grid_to_screen(x2, y2, &pt3);
        path_points[0] = pt1;
        path_points[1] = pt2;
        path_points[2] = pt3;
        path_point_count = 3;
        return true;
    }
    if (game_grid[y2][x1] == 0 && is_line_clear(x1, y1, x1, y2) && is_line_clear(x1, y2, x2, y2))
    {
        grid_to_screen(x1, y1, &pt1);
        grid_to_screen(x1, y2, &pt2);
        grid_to_screen(x2, y2, &pt3);
        path_points[0] = pt1;
        path_points[1] = pt2;
        path_points[2] = pt3;
        path_point_count = 3;
        return true;
    }

    for (uint16_t x = 0; x < GRID_COLS; x++)
    {
        if (x != x1 && x != x2 && game_grid[y1][x] == 0 && game_grid[y2][x] == 0 &&
            is_line_clear(x1, y1, x, y1) && is_line_clear(x, y1, x, y2) && is_line_clear(x, y2, x2, y2))
        {
            grid_to_screen(x1, y1, &pt1);
            grid_to_screen(x, y1, &pt2);
            grid_to_screen(x, y2, &pt3);
            grid_to_screen(x2, y2, &pt4);
            path_points[0] = pt1;
            path_points[1] = pt2;
            path_points[2] = pt3;
            path_points[3] = pt4;
            path_point_count = 4;
            return true;
        }
    }
    for (uint16_t y = 0; y < GRID_ROWS; y++)
    {
        if (y != y1 && y != y2 && game_grid[y][x1] == 0 && game_grid[y][x2] == 0 &&
            is_line_clear(x1, y1, x1, y) && is_line_clear(x1, y, x2, y) && is_line_clear(x2, y, x2, y2))
        {
            grid_to_screen(x1, y1, &pt1);
            grid_to_screen(x1, y, &pt2);
            grid_to_screen(x2, y, &pt3);
            grid_to_screen(x2, y2, &pt4);
            path_points[0] = pt1;
            path_points[1] = pt2;
            path_points[2] = pt3;
            path_points[3] = pt4;
            path_point_count = 4;
            return true;
        }
    }

    return false;
}

/* 画路径 */
static void draw_path_line(void)
{
    if (path_line == NULL)
    {
        path_line = lv_line_create(lv_scr_act());
        lv_obj_set_style_line_width(path_line, 3, 0);
        lv_obj_set_style_line_color(path_line, lv_color_hex(0xFF0000), 0);
        lv_obj_set_style_line_rounded(path_line, true, 0);
    }
    lv_line_set_points(path_line, path_points, path_point_count);
    lv_obj_clear_flag(path_line, LV_OBJ_FLAG_HIDDEN);
    lv_timer_t *timer = lv_timer_create(hide_path_line_cb, 200, NULL);
    lv_timer_set_repeat_count(timer, 1);
}

static void hide_path_line_cb(lv_timer_t *timer)
{
    if (path_line)
        lv_obj_add_flag(path_line, LV_OBJ_FLAG_HIDDEN);
}

/* 图标点击事件 */
static void icon_event_cb(lv_event_t *e)
{

    buzz_event(3,75);
    lv_obj_t *btn = lv_event_get_target(e);

    for (uint16_t r = 0; r < GRID_ROWS; ++r)
    {
        for (uint16_t c = 0; c < GRID_COLS; ++c)
        {
            if (icon_btns[r][c] == btn)
            {
                if (first_select.x == -1)
                {
                    first_select.x = c;
                    first_select.y = r;
                    lv_obj_set_style_bg_opa(icon_btns[r][c], LV_OPA_70, 0);
                }
                else
                {
                    uint16_t x1 = first_select.x, y1 = first_select.y;
                    uint16_t x2 = c, y2 = r;

                    if (game_grid[y1][x1] != 0 && can_connect(x1, y1, x2, y2))
                    {
                        draw_path_line();

                        game_grid[y1][x1] = 0;
                        game_grid[y2][x2] = 0;
                        lv_obj_add_flag(icon_btns[y1][x1], LV_OBJ_FLAG_HIDDEN);
                        lv_obj_add_flag(icon_btns[y2][x2], LV_OBJ_FLAG_HIDDEN);

                        pairs_remaining--;
                        lv_label_set_text_fmt(label_pairs, "Remains:%d", pairs_remaining);

                        // 通关检查
                        if (pairs_remaining == 0)
                        {
                            printf("current_level:%d\n", current_level);
                            // 更新关卡状态：当前关卡完成，下一关解锁
                            if (current_level <= TOTAL_LEVELS)
                            {
                                level_status[current_level - 1] = LEVEL_COMPLETED;
                                if (current_level < TOTAL_LEVELS &&
                                    level_status[current_level + 1] == LEVEL_LOCKED)
                                {
                                    level_status[current_level] = LEVEL_UNLOCKED;
                                }
                            }

                            for (uint8_t i = 0; i < TOTAL_LEVELS; i++)
                            {
                                printf("%d\n", level_status[i]);
                            }
                            show_win_dialog(); // 显示通关对话框
                        }
                    }

                    lv_obj_set_style_bg_opa(icon_btns[y1][x1], LV_OPA_100, 0);
                    first_select.x = first_select.y = -1;
                }
                return;
            }
        }
    }
}

static void show_win_dialog(void)
{
    if (win_dialog)
    {
        lv_obj_del(win_dialog);
        win_dialog = NULL; // 重要：将指针置为NULL
    }

    win_dialog = lv_obj_create(lv_scr_act());
    lv_obj_set_size(win_dialog, 480, 320);
    lv_obj_center(win_dialog);
    lv_obj_clear_flag(win_dialog, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_style_pad_all(win_dialog, 15, 0); // 直接在主弹窗设置内边距

    lv_obj_t *title = lv_label_create(win_dialog);
    lv_label_set_text_fmt(title, "Level %d Completed!", current_level);
    lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
    lv_obj_set_width(title, 230); // 宽度减去两边内边距
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 30);

    lv_obj_t *desc = lv_label_create(win_dialog);
    lv_label_set_text(desc, "Great job!");
    lv_obj_set_style_text_font(desc, &lv_font_montserrat_16, 0);
    lv_obj_set_style_text_align(desc, LV_TEXT_ALIGN_CENTER, 0);
    lv_obj_set_width(desc, 270);
    lv_obj_align_to(desc, title, LV_ALIGN_OUT_BOTTOM_MID, 0, 20);

    lv_obj_t *btn_cont = lv_obj_create(win_dialog);
    lv_obj_set_flex_flow(btn_cont, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(btn_cont, LV_FLEX_ALIGN_SPACE_EVENLY, 0, 0);
    lv_obj_set_size(btn_cont, 300, 100);
    lv_obj_align_to(btn_cont, desc, LV_ALIGN_OUT_BOTTOM_MID, 0, 40);

    // 返回按钮
    lv_obj_t *back_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(back_btn, 120, 40);
    lv_obj_set_style_bg_color(back_btn, lv_color_hex(0xF44336), 0);
    lv_obj_set_style_radius(back_btn, 8, 0);
    lv_obj_set_style_shadow_opa(back_btn, LV_OPA_30, 0);

    lv_obj_t *back_txt = lv_label_create(back_btn);
    lv_label_set_text(back_txt, "Main Menu");
    lv_obj_center(back_txt);
    lv_obj_add_event_cb(back_btn, return_to_main, LV_EVENT_CLICKED, NULL);

    // 下一关按钮（非最后一关）
    if (current_level < TOTAL_LEVELS)
    {
        lv_obj_t *next_btn = lv_btn_create(btn_cont);
        lv_obj_set_size(next_btn, 120, 40);
        lv_obj_add_event_cb(next_btn, go_to_next_level, LV_EVENT_CLICKED, NULL);
        lv_obj_set_style_bg_color(next_btn, lv_color_hex(0x4CAF50), 0);
        lv_obj_set_style_radius(next_btn, 8, 0);
        lv_obj_set_style_shadow_opa(next_btn, LV_OPA_30, 0);

        lv_obj_t *next_txt = lv_label_create(next_btn);
        lv_label_set_text(next_txt, "Next Level");
        lv_obj_center(next_txt);
    }
}

// 返回主菜单处理
static void return_to_main(lv_event_t *e)
{
      buzz_event(5,100);
    create_start_menu();
    lv_scr_load(main_menu_screen);

    if (win_dialog)
    {
        lv_obj_del(win_dialog);
        win_dialog = NULL; // 将指针置为NULL
    }
}

// 进入下一关处理
static void go_to_next_level(lv_event_t *e)
{

    buzz_event(6,100);
    if (current_level < TOTAL_LEVELS)
    {
        current_level++;
        custom_start_game(); // 初始化下一关
        if (win_dialog)
        {
            lv_obj_del(win_dialog);
            win_dialog = NULL; // 将指针置为NULL
        }
    }
}